<template>
  <div class="form-single-fragment" style="position: relative;">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" size="mini" label-position="right">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="taskName">
            <el-input class="input-item" v-model="ruleForm.taskName" placeholder="请输入" maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="执行人" prop="executeUserId">
            <el-select v-model="ruleForm.executeUserId" filterable placeholder="请选择">
              <el-option v-for="item in listUsers" :key="item.userId"
              :label="item.showName" :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参与人">
            <el-select v-model="ruleForm.participateUserId" filterable placeholder="请选择">
              <el-option v-for="item in listUsers" :key="item.userId"
              :label="item.showName" :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划回款金额（元）" prop="backAmount">
            <el-input type="number" class="input-item"
              v-model="ruleForm.backAmount"
              placeholder="请输入" maxlength="20"
              oninput="if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}if(value<0){value='0'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划回款方式" prop="backMethod">
            <el-select v-model="ruleForm.backMethod" placeholder="请选择">
              <el-option label="汇款" :value="1"></el-option>
              <el-option label="现金" :value="2"></el-option>
              <el-option label="支票" :value="3"></el-option>
              <el-option label="支付宝" :value="4"></el-option>
              <el-option label="微信支付" :value="5"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划回款时间" prop="backDate">
            <el-date-picker v-model="ruleForm.backDate" type="date" placeholder="选择日期"
            format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作流程" prop="businessFlowId">
            <el-select v-model="ruleForm.businessFlowId" placeholder="请选择" @change="flowEntryChange">
              <el-option v-for="(item,index) in flowEntrylist" :key="index"
              :label="item.flowName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属项目" prop="projectId">
            <el-select v-model="ruleForm.projectId" placeholder="请选择">
              <el-option v-for="(item,index) in depositlist" :key="index"
              :label="item.projectName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="审核进度">
            <ProcessViewer ref="ProcessViewers" :style="{height: (getMainContextHeight - 500) + 'px'}"
              :xml="processXml"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务描述">
            <el-input type="textarea" class="input-item" rows="4" v-model="ruleForm.taskDesc" placeholder="请输入" maxlength="20"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="任务日志">
            <el-scrollbar style="height:15vh;">
              <el-timeline>
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :timestamp="activity.createTime">
                  {{activity.userName}}：{{activity.content}}
                </el-timeline-item>
              </el-timeline>
            </el-scrollbar>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item style="padding: 20px 0;">
            <el-button @click="onCancel(false)">取消</el-button>
            <el-button type="danger" @click="handleDelete()" v-if="tasksId">删除</el-button>
            <el-button type="primary" @click="submitForm()">确定</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { Contracts, Administration, BusinessFlow } from '@/api/projectAdministration.js';
import { Customers } from '@/api/commercial.js';
import { SysUserController } from '@/api';
import ProcessViewer from '@/views/workflow/components/ProcessViewer.vue';
import { mapGetters } from 'vuex';
export default {
  name: 'ContractsTasksAdd',
  components: { ProcessViewer },
  props: {
    tasksId: {
      default: undefined
    },
    businessType: {
      default: undefined
    },
    contractId: {
      default: undefined
    }
  },
  data () {
    return {
      loading: false,
      isShowloading: false,
      processXml: undefined,
      tableData: [],
      listUsers: [],
      customerlist: [],
      situation: 1,
      depositlist: [],
      flowEntrylist: [],
      flowEntrys: '',
      activities: [],
      ruleForm: {
        taskName: '',
        executeUserId: '',
        participateUserId: '',
        backAmount: '',
        backMethod: '',
        backDate: '',
        businessFlowId: '',
        projectId: '',
        taskDesc: ''
      },
      rules: {
        taskName: [{ required: true, message: '请输入', trigger: 'blur' }],
        executeUserId: [{ required: true, message: '请选择', trigger: 'change' }],
        participateUserId: [{ required: true, message: '请选择', trigger: 'change' }],
        backAmount: [{ required: true, message: '请输入', trigger: 'blur' }],
        backMethod: [{ required: true, message: '请选择', trigger: 'change' }],
        backDate: [{ required: true, message: '请选择', trigger: 'change' }],
        businessFlowId: [{ required: true, message: '请选择', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    };
  },
  created () {
  },
  computed: {
    isEdit () {
      return this.tasksId != null && this.tasksId !== '';
    },
    ...mapGetters(['getMainContextHeight'])
  },
  mounted () {
    this.listGroupUser()
    this.loadCustomerList()
    this.loadlistForDeposit()
    this.loadflowWidgetData()
    if (this.isEdit) {
      this.loadDetailWidgetData()
      this.loadTasklogWidgetData()
    }
  },
  methods: {
    /**
     * 合同任务详情
     */
    loadDetailWidgetData () {
      let params = {
        id: this.tasksId
      };
      return new Promise((resolve, reject) => {
        Contracts.taskview(this, params).then(res => {
          this.ruleForm = res.data
          this.processXml = res.data.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 任务日志
     */
    loadTasklogWidgetData () {
      let params = {
        taskId: this.tasksId,
        logType: 4
      };
      return new Promise((resolve, reject) => {
        Administration.tasklog(this, params).then(res => {
          this.activities = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 项目列表
     */
    loadlistForDeposit () {
      let params = {
        contractId: this.$route.query.contractId ? this.$route.query.contractId : this.contractId
      }
      return new Promise((resolve, reject) => {
        Administration.listForBackPlan(this, params).then(res => {
          this.depositlist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 审核流程列表
     */
    loadflowWidgetData () {
      let params = {
        businessStage: 3,
        businessType: this.$route.query.businessType ? this.$route.query.businessType : this.businessType
      }
      return new Promise((resolve, reject) => {
        BusinessFlow.lists(this, params).then(res => {
          this.flowEntrylist = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 审核流程选择
     */
    flowEntryChange (value) {
      this.flowEntrylist.forEach(item => {
        if (item.id === value) {
          this.processXml = item.bpmnXml
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.ProcessViewers.processReZoom()
            });
          }, 500)
        }
      })
    },
    /**
     * 客户列表
     */
    loadCustomerList () {
      let params = ''
      return new Promise((resolve, reject) => {
        Customers.lists(this, params).then(res => {
          this.list = res.data
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 人员列表
     */
    listGroupUser () {
      let params = {
        orderParam: [{fieldName: 'createTime', asc: 1}],
        sysUserDtoFilter: {}
      };
      return new Promise((resolve, reject) => {
        SysUserController.list(this, params).then(res => {
          this.listUsers = res.data.dataList
        }).catch(e => {
          reject(e);
        });
      });
    },
    /**
     * 提交表单
     */
    submitForm () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.isShowloading = true;
          this.ruleForm.contractId = this.$route.query.contractId ? this.$route.query.contractId : this.contractId
          if (this.isEdit) { // 修改
            let params = {
              updateDto: this.ruleForm
            };
            return new Promise((resolve, reject) => {
              Contracts.taskupdate(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '修改成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          } else { // 添加
            let params = {
              addDto: this.ruleForm
            };
            return new Promise((resolve, reject) => {
              Contracts.taskadd(this, params).then(res => {
                this.$message({
                  showClose: true,
                  message: '操作成功！',
                  type: 'success'
                });
                this.onCancel(true);
              }).catch(e => {
                reject(e);
              });
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 删除
    handleDelete () {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = {
          id: this.tasksId
        }
        return new Promise((resolve, reject) => {
          Contracts.taskdelete(this, params).then(res => {
            this.$message.success('删除成功！');
            this.onCancel(true);
          }).catch(e => {
            reject(e);
          });
        });
      })
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    }
  }
}
</script>

<style scoped>
h4{margin-bottom: 0;}
.table_container{margin: 10px 0;}
.form-single-info{display: flex;justify-content: center;}
.el-form-info{box-shadow: 0 0 10px rgba(0,0,0,0.05);padding: 20px;}
.el-form-info strong{margin: 0 10px;}
</style>
